'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
const serviceName = 'postJoin'
class RouterController extends Controller {
    async index() {
        const { query, service } = this.ctx;
        let { pageNum, pageSize, post_id,company_user_id } = query;
        let page = Number(pageNum) || 1;
        let size = Number(pageSize) || 10;
        const where = {

        };
        if (post_id) {
            where.post_id = post_id
        }
        if (company_user_id) {
            where.company_user_id = company_user_id
        }
        const list = await service[serviceName].getPage(where, page, size);
        this.ctx.success(list);
    }
    async allList() {
        const { service } = this.ctx;
        const { query } = this.ctx;
        const { category, is_read, company_user_id} = query;
        let where = {}
        if (company_user_id) {
            // where.company_user_id = company_user_id 且在user表中 role = 2
            where.company_user_id = company_user_id
        }
        if (category) {
            where.category = category
        }
        if (is_read) {
            where.is_read = is_read
        }
        const list = await service[serviceName].allList(where);
        this.ctx.success(list);
    }
    async create() {
        const { ctx } = this;
        const data = ctx.request.body;
        const res = await ctx.service[serviceName].create(data);
        ctx.success(res, 200);
    }
    async update() {
        const { ctx } = this;
        const id = ctx.params.id;
        const infos = ctx.request.body;
        if (!id) throw new Error('必须传递ID参数');
        if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
        await ctx.service[serviceName].update(id, infos);
        const res = await ctx.service[serviceName].findOne(id);
        ctx.success(res, 200);
    }
    async destroy() {
        const uid = Number(this.ctx.params.id);
        if (!uid) throw new Error('ID 有误');
        await this.ctx.service[serviceName].deleteById(uid);
        this.ctx.success(uid); // 删除成功返回被删除的用户ID
    }
    async show() {
        const { params, service } = this.ctx;
        const findItem = await service[serviceName].findOne(params.id);
        this.ctx.success(findItem);
    }
}

module.exports = RouterController;
